﻿using Senparc.CO2NET.Helpers;
using Senparc.Weixin;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MvcExtension;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Wei.Attributes;
using Wei.Controllers;
using Wei.Tool;

namespace Wei.Models
{
    /// <summary>
    /// 测试任务
    /// </summary>
    [AutoTask(EnterMethod = "StartTask", StartTime = "2016-12-28 10:45:00")]
    public class TestTask
    {
        protected static WeiXinController target;
        protected static Stream inputStream;
        static string xmlTextFormat = @"<xml>
    <ToUserName><![CDATA[gh_7d7b3eb39f02]]></ToUserName>
    <FromUserName><![CDATA[o8xBgwqHtt94q6HD1ArswdpLsl3Y]]></FromUserName>
    <CreateTime>{{0}}</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[{0}]]></Content>
    <MsgId>5832509444155992350</MsgId>
</xml>
";
        /// <summary>
        ////// </summary>
        public static void StartTask()
        {

            //Init(xmlTextFormat);//初始化

            //var timestamp = "itsafaketimestamp";
            //var nonce = "whateveryouwant";
            //var signature = Senparc.Weixin.MP.CheckSignature.GetSignature(timestamp, nonce, Config.SenparcWeixinSetting.Token);

            //DateTime st = DateTime.Now;
            ////这里使用MiniPost，绕过日志记录

            //var postModel = new PostModel()
            //{
            //    Signature = signature,
            //    Timestamp = timestamp,
            //    Nonce = nonce,
            //};
            //var actual = target.MiniPost(postModel) as FixWeixinBugWeixinResult;

            Log.Write_Log_For_New_File("开始写入自动任务，时间：" + DateTime.Now.ToString("yyyyMMddHHmmss") + System.Environment.NewLine, "自动任务");
        }

        /// <summary>
        /// 初始化控制器及相关请求参数
        /// </summary>
        /// <param name="xmlFormat"></param>
        protected static void Init(string xmlFormat)
        {
            //target = StructureMap.ObjectFactory.GetInstance<WeixinController>();//使用IoC的在这里必须注入，不要直接实例化
            target = new WeiXinController();

            inputStream = new MemoryStream();

            var xml = string.Format(xmlFormat, DateTimeHelper.GetWeixinDateTime(DateTime.Now));
            var bytes = System.Text.Encoding.UTF8.GetBytes(xml);

            inputStream.Write(bytes, 0, bytes.Length);
            inputStream.Flush();
            inputStream.Seek(0, SeekOrigin.Begin);

            //target.SetFakeControllerContext(inputStream);
        }


    }
}